package com.ken.android.music.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ken.android.music.mvp.B.BaseFragment;
import com.ken.android.music.mvp.B.BasePresenter;
import com.ken.android.music.view.activity.MusicListActivity;
import com.ken.android.music.view.adapter.RecyclerViewAdapter;
import com.ken.android.music.consts.Config;
import com.ken.android.music.db.ListsInfoDao;
import com.ken.android.music.model.ListInfo;
import com.ken.android.music.R;
import com.ken.android.music.view.presenter.HomeFragmentContract;
import com.ken.android.music.view.presenter.HomeFragmentPresenter;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


/**
 * Created by axnshy on 16/5/20.
 */
@ContentView(R.layout.home_top_fragment)
public class HomeFragment extends BaseFragment<HomeFragmentContract.View, HomeFragmentPresenter> implements View.OnClickListener,HomeFragmentContract.View {
    private List<ListInfo> mMusicArray = new ArrayList<>();;
    private LinearLayout linearLayout1;
    private TextView txtNum1;

    private int screenWidth;
    private int screenHeight;

    @ViewInject(R.id.recycler_music_list)
    private RecyclerView recyclerView;
    @ViewInject(R.id.tv_addlist)
    private TextView newMusicListTx;
    private RecyclerViewAdapter mRecyclerAdapter;

    private View view;

    private LayoutInflater inflater;

    private AlertDialog dialog;

    private String AvatarUri=null;

    private ImageView showAvatar;

    @Override
    public int onSetContent() {
        return R.layout.home_top_fragment;
    }

    @Override
    public void initView(View view) {
        linearLayout1 = (LinearLayout) view.findViewById(R.id.id_top_home_linearlayout1);
        txtNum1 = (TextView) view.findViewById(R.id.tv_music_count1);
        linearLayout1.setOnClickListener(this);
        newMusicListTx= (TextView) view.findViewById(R.id.tv_addlist);
        newMusicListTx.setOnClickListener(this);
        txtNum1.setText(" 个");
        txtNum1.setTextColor(Color.parseColor("#FFFFFF"));
    }

    @Override
    public void onClick(View v) {
        int viewID = v.getId();
        switch (viewID) {
            case R.id.id_top_home_linearlayout1: {
                Intent intent = new Intent(getContext(), MusicListActivity.class);
                ListInfo info = new ListInfo();
                info.setListId(-1);
                info.setListName("Local");
                intent.putExtra("listinfo",info);
                startActivity(intent);
                break;
            }
            case R.id.tv_addlist:
                final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.dialog_add_music_list, null);
                builder.setView(layout);
                dialog = builder.create();
                final EditText inputListName = (EditText) layout.findViewById(R.id.et_input_music_list_name);
                TextView cancelTx = (TextView) layout.findViewById(R.id.tv_cancel);
                TextView confirm = (TextView) layout.findViewById(R.id.tv_confirm);
                final Button addAvatar= (Button) layout.findViewById(R.id.btn_select_background_from_lib);
                showAvatar = (ImageView) layout.findViewById(R.id.iv_show_list_avatar);

                cancelTx.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                    }
                });
                confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                ListsInfoDao.getDAO().addMusicList(view.getContext(), inputListName.getText().toString().trim(),AvatarUri);
                                Message msg = Message.obtain();
                                msg.obj = new ListInfo(inputListName.getText().toString(), 0,AvatarUri);
                                msg.what = 1;
                                mHandler.sendMessage(msg);
                                dialog.dismiss();
                            }
                        }).start();
                    }
                });
                addAvatar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        addAvatar.setVisibility(View.INVISIBLE);
                        Intent picture = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(picture, 101);
                    }
                });
                dialog.show();
        }
    }

    @Override
    public HomeFragmentPresenter createPresenter() {
        return new HomeFragmentPresenter();
    }

    /*
    * http://blog.csdn.net/wangliblog/article/details/22501141
    * */
    public void getAndroidScreenProperty() {
        WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;// 屏幕宽度（像素）
        screenHeight = dm.heightPixels;
        /*int width = dm.widthPixels;// 屏幕宽度（像素）
        int height = dm.heightPixels; // 屏幕高度（像素）*/
        /*float density = dm.density;//屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = dm.densityDpi;//屏幕密度dpi（120 / 160 / 240）
        //屏幕宽度算法:屏幕宽度（像素）/屏幕密度
        screenWidth = (int) (width / density);//屏幕宽度(dp)
        screenHeight = (int) (height / density);//屏幕高度(dp)*/
        Log.e("TAG", screenWidth + "======" + screenHeight);
    }


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mMusicArray.add((ListInfo) msg.obj);
                    mRecyclerAdapter .notifyItemChanged(mMusicArray.size()-1);
                    break;
                case 0:
                    if(recyclerView==null) {
                        mMusicArray = (List<ListInfo>) msg.obj;
//                    mListsList.add(0,new ListsInfo());
                        getAndroidScreenProperty();
                        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_music_list);
                        mRecyclerAdapter = new RecyclerViewAdapter(view.getContext(), mMusicArray, screenWidth, screenHeight);
                        mRecyclerAdapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                int _id = mMusicArray.get(position).getListId();
                                Intent intent = new Intent(view.getContext(), MusicListActivity.class);
                                intent.putExtra("listinfo", mMusicArray.get(position));
                                startActivity(intent);
                            }
                            @Override
                            public void onItemLongClick(View view, int position) {

                            }
                        });
                        recyclerView.setAdapter(mRecyclerAdapter);
                        GridLayoutManager manager = new GridLayoutManager(view.getContext(), 3);
                        recyclerView.setLayoutManager(manager);
                    }
                    break;
                default:
                    break;
            }

        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == Activity.RESULT_OK && null != data) {

            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = view.getContext().getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            AvatarUri= picturePath;
            showAvatar.setImageURI(Uri.parse(picturePath));
        }
    }
}
